package com.itheima.im.socket.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.itheima.im.socket.R;
import com.itheima.im.socket.adapter.ContactAdapter;
import com.itheima.im.socket.bean.QQBuddy;
import com.itheima.im.socket.bean.QQBuddyList;
import com.itheima.im.socket.bean.QQMessage;
import com.itheima.im.socket.bean.QQMessageType;
import com.itheima.im.socket.core.OnReceiveMsgListener;
import com.itheima.im.socket.utils.ThreadUtils;

public class QQContactActivity extends Activity {

	@InjectView(R.id.contactlistview)
	ListView contactlistview;

	private ContactAdapter adapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact);
		ButterKnife.inject(this);
		MyApp.conn.addOnReceiveMsgListener(listener);
		// 获取意图
		Intent intent = getIntent();
		String json = intent.getStringExtra("json");
		System.out.println(json);
		QQBuddyList temp = (QQBuddyList) new QQBuddyList().fromJson(json);
		setAdapterOrNitifyDataSetChange(temp);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		MyApp.conn.removeOnReceiveMsgListener(listener);
	}

	private OnReceiveMsgListener listener = new OnReceiveMsgListener() {
		@Override
		public void onReceive(final QQMessage msg) {// 子线程
			ThreadUtils.runUIThread(new Runnable() {
				@Override
				public void run() {
					// 控件 null
					if (QQMessageType.MSG_TYPE_BUDDYLIST.equals(msg.type)) {
						String json = msg.content;
						QQBuddyList temp = (QQBuddyList) new QQBuddyList().fromJson(json);
						setAdapterOrNitifyDataSetChange(temp);
					}
					
				}
			});
		}
	};
	// new Thread().start();
	public void setAdapterOrNitifyDataSetChange(QQBuddyList temp) {
		list.buddyList.clear();
		list.buddyList.addAll(temp.buddyList);
		if (adapter == null) {
			if (list.buddyList.size() < 1) {
				return;
			}
			// 06-12 03:05:15.215: I/System.out(2120):
			// {"buddyList":[{"account":101,"nick":"QQ 1","avatar":0}]}
			adapter = new ContactAdapter(this, list.buddyList);
			contactlistview.setAdapter(adapter);
			
			contactlistview.setOnItemClickListener(new ListView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

					//
					QQBuddy buddy=adapter.getItem(position);
					
					Intent intent=new Intent(getBaseContext(),ChatActivity.class);
					
					intent.putExtra("tochatNick", buddy.nick);
					intent.putExtra("tochatAccount", buddy.account);//取出长整型
					startActivity(intent);
				}
			});
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	private QQBuddyList list = new QQBuddyList();
}
